import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useLoadingStore } from '@/stores'
export const _axios = axios.create({
	baseURL: 'http://127.0.0.1:8081'
})
export const request = (url, method, params, callback) => {
	const loadingStore = useLoadingStore()
	loadingStore.open()
	const axios_config = {
		url,
		method
	}
	if ('post' === method) {
		const formData = new FormData()
		for (const key in params) {
			formData.append(key, params[key])
		}
		axios_config.data = formData
	} else {
		axios_config.params = params
	}
	_axios.request(axios_config).then(response => {
		if (response.data.code === 200) {
			if (response.data.message) {
				ElMessage.success(response.data.message)
			}
			callback(response.data.content)
		} else {
			ElMessage.error(response.data.message)
		}
	}).catch(error => {
		console.dir(error)
		ElMessage.error('网络请求错误')
	}).finally(() => {
		loadingStore.close()
	})
	
}
export const get = (url, params, callback) => request(url, 'get', params, callback)
export const post = (url, params, callback, formObj = null) => {
	if (formObj) {
		formObj.validate(valid => {
			if (valid) {
				request(url, 'post', params, callback)
			}
		})
	} else {
		request(url, 'post', params, callback)
	}
} 
